package com.aggregate.pay.weixin.test.client;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.weixin.support.HttpClient;
import com.aggregate.pay.weixin.support.Merch;

public class WeixinHttpClient implements HttpClient {
	
	private static Logger log = LoggerFactory.getLogger(WeixinHttpClient.class);
	
	private static final String CHARSET = "UTF-8";
	
	private Merch merch;
	
	public WeixinHttpClient(Merch merch) {
		this.merch = merch;
	}
	
	@Override
	public String post(String serverPath, String postBody) {
		log.debug("请求地址：{}", serverPath);
		log.debug("请求内容：{}", postBody);
		Header header = new BasicHeader("Content-Type", 
				"application/x-www-form-urlencoded; charset=" + CHARSET);
		HttpUriRequest httpUriRequest = RequestBuilder
				.post()
				.setHeader(header)
				.setUri(serverPath)
				.setEntity(new StringEntity(postBody, CHARSET))
				.build();
		CloseableHttpClient httpClient = getHttpClient(serverPath);
		CloseableHttpResponse response;
		try {
			response = httpClient.execute(httpUriRequest);
			int status = response.getStatusLine().getStatusCode();
			log.debug("远程接口返回状态：{}", response.getStatusLine());
	        if (status == 200) {
	        	String resBody = EntityUtils.toString(response.getEntity(), CHARSET);
	        	log.debug("响应内容：{}", resBody);
				return resBody;
	        } 
		} catch (Exception e) {
			log.error("远程接口调用失败", e);
		} 
		return null;
	}
	
	private CloseableHttpClient getHttpClient(String serverPath) {
		if (serverPath.indexOf("secapi/pay/refund") == -1) {
			return HttpClientFactory.createHttpClient();
		} else {
			KeyStore keyStore = null;
			try {
				keyStore = initCert(merch.mchId(), merch.certificate());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return HttpClientFactory.createKeyMaterialHttpClient(keyStore, merch.mchId());
		}
		
	}

	private KeyStore initCert(String mchId, String certPath) throws Exception {
		// 证书密码，默认为商户ID
		String key = mchId;
		// 证书的路径
		String path = certPath;
		// 指定读取证书格式为PKCS12
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		// 读取本机存放的PKCS12证书文件
		FileInputStream instream = new FileInputStream(new File(path));
		try {
			// 指定PKCS12的密码(商户ID)
			keyStore.load(instream, key.toCharArray());
		} finally {
			instream.close();
		}
		
		return keyStore;
	}
}
